package com.beta.cust.bind.datasync.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beta.cat.service.RedissonService;
import com.beta.cust.bind.datasync.constant.BusinessConstant;
import com.beta.cust.bind.datasync.constant.RedisConstant;
import com.beta.cust.bind.datasync.dto.SelectReq;
import com.beta.cust.bind.datasync.mapper.AuthCorpInfoMapper;
import com.beta.cust.bind.datasync.mapper.entity.AuthCorpInfo;
import com.beta.cust.bind.datasync.service.AuthCorpInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * <p>
 * 下游企业 服务实现类
 * </p>
 *
 * @author wangjiang
 * @since 2024-04-11
 */
@Service
public class AuthCorpInfoServiceImpl extends ServiceImpl<AuthCorpInfoMapper, AuthCorpInfo> implements AuthCorpInfoService {

    @Autowired
    private RedissonService redissonService;

    @Override
    public IPage<AuthCorpInfo> selectPage(SelectReq req) {
        Page<AuthCorpInfo> page = new Page<>(req.getCurrentPage(), req.getPageSize());
        return baseMapper.selectPage(page, new LambdaQueryWrapper<AuthCorpInfo>()
                .eq(AuthCorpInfo::getDelFlag, BusinessConstant.IS_NOT_DEL_FLAG)
                .orderByAsc(AuthCorpInfo::getId)
                .gt(null != req.getId(), AuthCorpInfo::getId, req.getId()));
    }

    @Override
    public String getAgentIdByCorpId(String corpId) {
        if (StringUtils.isEmpty(corpId)) {
            return StringUtils.EMPTY;
        }
        String redisKey = String.format(RedisConstant.AUTH_CORP_KEY, corpId);
        AuthCorpInfo redisResult = redissonService.get(redisKey, AuthCorpInfo.class);
        if (null == redisResult) {
            redisResult = getOne(new LambdaQueryWrapper<AuthCorpInfo>()
                    .eq(AuthCorpInfo::getCorpId, corpId).eq(AuthCorpInfo::getDelFlag, BusinessConstant.IS_NOT_DEL_FLAG), false);
            if (null == redisResult) {
                return StringUtils.EMPTY;
            }
            redissonService.setJson(redisKey, redisResult);
            redissonService.expire(redisKey, Duration.ofHours(3));
        }
        return redisResult.getAgentId();
    }
}
